<template>
  <BasicModal @register="registerModal" v-bind="$attrs" wrapClassName="form-modal" destroy-on-close>
    <template #title>
      <div class="step-form-form">
        <a href="http://glcs.51wit.com/" target="_blank">
          <img src="/src/assets/images/design/logo.png" />
        </a>
        <span>•</span>
        <span>{{ t('移动设计 - 功能设计页') }}</span>
        <a-steps :current="current" size="mini">
          <a-step :title="t('基本信息')" />
          <a-step :title="t('表单设计')" />
          <a-step :title="t('界面设计')" />
          <a-step :title="t('代码预览')" />
          <a-step :title="t('菜单设置')" />
        </a-steps>
        <div class="btn-box">
          <a-button @click="handleStepPrev" v-show="current !== 0">{{ t('上一步') }}</a-button>
          <a-button type="primary" @click="handleSaveDraft" v-show="current > 2">{{
            t('保存草稿')
          }}</a-button>
          <a-button type="primary" @click="handleStepNext" v-show="current < 4">
            {{ t('下一步') }}
          </a-button>
          <a-button type="primary" @click="handleCodeGenerator" v-show="current === 4">
            {{ t('完成') }}
          </a-button>
          <a-button type="primary" danger @click="handleClose">{{ t('关闭') }}</a-button>
        </div>
      </div>
    </template>
    <div class="step-container">
      <TableConfigStep ref="tableConfigStepRef" v-if="current === 0" />
      <FormDesignStep ref="formDesignStepRef" v-if="current === 1" />
      <ViewDesignStep ref="viewDesignStep" :isUpdate="!!templateId" v-show="current === 2" />
      <PreviewCodeStep ref="previewCodeStep" v-show="current === 3" />
      <MenuConfigStep ref="menuConfigStep" v-show="current === 4" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, defineAsyncComponent, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';

  import { buildAppFormProps } from '/@/utils/helper/designHelper';
  import { buildAppCode } from '/@/utils/helper/generatorHelper';
  import { AppFuncModel } from '/@/api/system/generator/model';
  import { useUserStore } from '/@/store/modules/user';
  import { LoadingBox } from '/@/components/ModalPanel/index';
  import { MenuConfig } from '/@/model/generator/menuConfig';
  import { FormJson } from '/@/model/generator/codeGenerator';
  import { FormEventColumnConfig } from '/@/model/generator/formEventConfig';
  import * as antd from '/@/components/Designer/src/types';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { AppFormProps } from '/@/model/generator/appFormConfig';
  import { addMobileFunc, editMobileFuncData, getMobileFuncInfo } from '/@/api/mobileDesign';

  const { t } = useI18n();
  const TableConfigStep = defineAsyncComponent({
    loader: () => import('./TableConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const FormDesignStep = defineAsyncComponent({
    loader: () => import('./FormDesignStep.vue'),
    loadingComponent: LoadingBox,
  });

  const ViewDesignStep = defineAsyncComponent({
    loader: () => import('./ViewDesignStep.vue'),
    loadingComponent: LoadingBox,
  });
  const MenuConfigStep = defineAsyncComponent({
    loader: () => import('./MenuConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const PreviewCodeStep = defineAsyncComponent({
    loader: () => import('./PreviewCodeStep.vue'),
    loadingComponent: LoadingBox,
  });

  const userStore = useUserStore();
  const templateId = ref();
  const appMenuId = ref();
  const enabledMark = ref(1);
  const current = ref(0);
  const designType = ref('data');
  const mainTableName = computed(
    () => generatorConfig!.tableConfigs!.find((item) => item.isMain)!.tableName,
  );
  const tableConfigStepRef = ref();
  const formDesignStepRef = ref();

  const viewDesignStep = ref();
  const previewCodeStep = ref();
  const menuConfigStep = ref();
  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm))); //FormDesignStep -> designer和StructureConfigStep页面使用
  const tableInfo = ref<TableInfo[]>([]);

  const emit = defineEmits(['close', 'register', 'success']);
  let generatorConfig = reactive<GeneratorConfig>({
    databaseId: null, //数据库id
    listConfig: {
      isLeftMenu: false,
      queryConfigs: [],
      leftMenuConfig: {
        // isTree: false,
        datasourceType: 'static',
        listFieldName: undefined,
        apiConfig: {},
        dictionaryItemId: undefined,
        menuName: '',
        parentIcon: '',
        childIcon: '',
        staticData: [],
      },
      columnConfigs: [],
      buttonConfigs: [],
      defaultOrder: true,
      isPage: true,
    },
    tableConfigs: [],
    formJson: {} as FormJson,
    menuConfig: {} as MenuConfig,
    outputConfig: {
      creator: userStore.getUserInfo.name,
      isMenu: true,
      type: 0,
      funcType: 1,
      formObj: {
        formId: '',
      },
      createCode: false,
    },
    formEventConfig: {} as FormEventColumnConfig,
    isDataAuth: false,
    dataAuthList: [],
    formId: '',
  });
  provide<GeneratorConfig>('generatorConfig', generatorConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<Ref<number>>('current', current); //当前步骤
  provide<Ref<string>>('designType', designType);
  provide('widgetForm', widgetForm);
  provide<Ref<string>>('mainTableName', mainTableName);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    templateId.value = data.isUpdate ? data.id : '';
    appMenuId.value = data.isUpdate ? data.appMenuId : '';
    enabledMark.value = data.isUpdate ? data.enabledMark : 1;
    generatorConfig.outputConfig.funcType = 1;
    generatorConfig.outputConfig.formObj = undefined;
    generatorConfig.outputConfig.comment = '';
    generatorConfig.outputConfig.className = undefined;
    generatorConfig.outputConfig.outputArea = undefined;
    generatorConfig.databaseId = null;
    generatorConfig.isDataAuth = false;
    generatorConfig.dataAuthList = [];
    if (data.isUpdate) {
      let res: any = {};
      let jsonContent: any = {};
      res = await getMobileFuncInfo(data.id);

      jsonContent = JSON.parse(res.jsonContent);

      generatorConfig.databaseId = jsonContent.databaseId;
      generatorConfig.listConfig = jsonContent.listConfig;
      let filterBtn = [
        'batchdelete',
        'startwork',
        'batchSetUserId',
        'import',
        'export',
        'print',
        'templateprint',
      ];
      generatorConfig.listConfig.buttonConfigs = jsonContent.listConfig.buttonConfigs.filter(
        (o) => {
          return !filterBtn.includes(o.code);
        },
      );
      generatorConfig.formJson = jsonContent.formJson;
      generatorConfig.formId = jsonContent.formId;
      generatorConfig.tableConfigs = jsonContent.tableConfigs;
      generatorConfig.menuConfig = jsonContent.menuConfig;
      generatorConfig.outputConfig = jsonContent.outputConfig;
      generatorConfig.formEventConfig =
        jsonContent.formEventConfig || ({} as FormEventColumnConfig);
      widgetForm.value = jsonContent.formJson;
    }
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      maskClosable: false,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
  });

  //上一步
  function handleStepPrev() {
    current.value--;
  }
  //下一步
  async function handleStepNext() {
    const isOk = await stepValidate[current.value]();
    if (!isOk) {
      return;
    }
    current.value++;
  }

  async function handleSaveDraft() {
    menuConfigStep.value.getFormData();
    await setParams(-1);
    handleClose();
    emit('success');
  }
  async function handleCodeGenerator() {
    const isOk = await stepValidate[4]();
    if (!isOk) {
      return;
    }
    await setParams(enabledMark.value);
    handleClose();
    emit('success');
  }
  async function setParams(enabledMark) {
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }

    let frontCode = buildAppCode(
      generatorConfig,
      buildAppFormProps(generatorConfig.formJson) as AppFormProps,
      designType.value,
    );

    const data: AppFuncModel = {
      codeSchemaId: generatorConfig.outputConfig.formObj!.formId,
      codes: frontCode,
      enabledMark: enabledMark,
      formType: generatorConfig.outputConfig.funcType!,
      funcDescribe: generatorConfig.outputConfig.comment,
      funcModule: generatorConfig.outputConfig.outputArea,
      jsonContent: JSON.stringify(generatorConfig),
      menuConfigs: {
        code: generatorConfig.menuConfig?.code,
        name: generatorConfig.menuConfig?.name,
        remark: generatorConfig.menuConfig?.remark,
        sortCode: generatorConfig.menuConfig?.sortCode,
        icon: generatorConfig.menuConfig?.icon,
        categoryId: generatorConfig.menuConfig?.parentId,
      },
      remark: generatorConfig.outputConfig.remarks,
    };
    if (data.formType === 1) {
      data.isGeneratorCode = generatorConfig!.outputConfig!.createCode ? 1 : 0;
    }
    if (templateId.value) {
      data.id = templateId.value;
      data.appMenuId = appMenuId.value;
      await editMobileFuncData(data);
    } else {
      await addMobileFunc(data);
    }
  }
  const handleClose = () => {
    closeModal();
    current.value = 0;
    emit('close');
  };

  const stepValidate = {
    //数据表配置 验证
    0: () => tableConfigStepRef.value.validateStep(),
    1: () => formDesignStepRef.value.validateStep(),
    2: () => viewDesignStep.value.validateStep(),
    3: () => previewCodeStep.value.validateStep(),
    4: () => menuConfigStep.value.validateStep(),
  };
</script>
<style lang="less" scoped>
  @keyframes rotation {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }
  @keyframes rotationReverse {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(-360deg);
    }
  }

  :deep(.ant-steps-item-process) {
    .ant-steps-item-icon {
      border: 2px solid #fff;
      line-height: 30px;
      animation: rotation 4s linear infinite;
      position: relative;

      &::before {
        border: 2px dashed #1890ff;
        content: '';
        width: 36px;
        height: 36px;
        display: block;
        border-radius: 50%;
        position: absolute;
        left: -4px;
        top: -4px;
      }

      .ant-steps-icon {
        display: inline-block;
        animation: rotationReverse 4s linear infinite;
      }
    }
  }

  .step-form-content {
    padding: 24px;
    background-color: @component-background;
  }

  .step-form-form {
    display: flex;
    align-items: center;
    font-weight: 400;

    a {
      margin-left: -16px;
    }

    span {
      font-size: 16px;
      margin: 0 20px 0 -5px;
      white-space: nowrap;
    }

    :deep(.ant-steps) {
      width: calc(100% - 750px);
    }

    :deep(.ant-steps-item-container) {
      padding: 3px 0 3px 3px;
    }

    .btn-box {
      position: absolute;
      right: 10px;

      :deep(.ant-btn) {
        margin-right: 10px;
      }
    }
  }

  .step-container {
    height: 100%;
  }

  .step1 {
    padding: 0 14px;
    box-sizing: border-box;
  }
</style>
